/* ------------------------------------------------------------------------*
 *
 * ------------------------------------------------------------------------*/

#include "bsp.h"
#include "pincfg.h"
#include "at32f435_437_usart.h"
#include "os_obj.h"
#include "mbapp.h"
#include "com_def.h"
#include "bsp_cpu_it.h"
#include "bsp_uart_timer.h"
#include "pincfg.h"
//针对IO模块，超时改为50ms
// RS2
#define mbPORT USART3
#define mbURT_IRQn USART3_IRQn
#define mbISR MB_UART3_IRQHandler
#define mbObj mb.obj03
#define mbCmdBuff mb.CmdBuff03

// RS485 Dir-Pin
#define mbRxEnable()
#define mbTxEnable()

#include "bsp_mbport_gen.c"
mb_fun_api_make(mb03, mb.obj03);

/*****************************************************************************
 * @brief   mb port.
 * @param   none
 * @return  none
 * @ Pass/ Fail criteria: none
 *****************************************************************************/
static void mb_port_hal_cfg(void)
{
	intx_alloc();

	nvic_irq_set(mbURT_IRQn, 0x0F, 0);

	intx_disable();

	crm_periph_clock_enable(CRM_USART3_PERIPH_CLOCK, TRUE);
	crm_periph_reset(CRM_USART3_PERIPH_RESET, TRUE);
	crm_periph_reset(CRM_USART3_PERIPH_RESET, FALSE);

	intx_enable();
}

/*****************************************************************************
 * @brief   mb_cb_set
 * @param   none
 * @return  none
 * @ Pass/ Fail criteria: none
 *****************************************************************************/
static void mb_cb_set(void)
{
	intx_alloc();

	mbObj.slave.reg_coils_cb = &smb_reg_coils_cb;
	mbObj.slave.reg_discrete_cb = &smb_reg_discrete_cb;
	mbObj.slave.reg_hold_cb = &smb_reg_holding_cb;
	mbObj.slave.reg_input_cb = &smb_reg_input_cb;

	mmb_cmd_buff_init(&mbObj, mbCmdBuff, sizeof(mbCmdBuff) / sizeof(mbCmdBuff[0]), 16);

	intx_disable();

	mbObj.api = mb_api_name(mb03);

	intx_enable();
}

/*******************************************************************************
 * @brief: 
 * @param {*}
 * @return {*}
 ******************************************************************************/
static void _rtu_timer_run(void)
{
	mb_rtu_timer_run(&mbObj);
}

/*****************************************************************************
 * @brief   mb init .
 * @param   mbMode
 * @param   ulBaudRate
 * @param   eParity
 * @return  none
 * @ Pass/ Fail criteria: none
 *****************************************************************************/
void mb03_Init(mb_mode_type mbMode, uint32_t ulBaudRate, mb_parity_type eParity)
{
	// 禁用中断
	nvic_irq_set(mbURT_IRQn, 0x0F, 0);
	uart_timer.uart03 = 0;

	// 中断映射
	cpu_it.uart03 = mbISR;

	// 初始化
	mb_port_Init(mbMode, ulBaudRate, eParity);

	// 链接定时器任务
	uart_timer.uart03 = _rtu_timer_run;
	app_timer_task_add(uart03_timer_handle);
}
